package com.pkt.upload.service;


import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author: xinglongge
 * @Date: 2020/3/1 22 35
 * @Description:
 */
@Service
@Slf4j
public class UploadService {

    private static final List<String> CONTET_TYPES = Arrays.asList("image/gif", "image/jpeg", "image/png");
    private final FastFileStorageClient storageClient;

    @Autowired
    public UploadService(FastFileStorageClient storageClient) {
        this.storageClient = storageClient;
    }

    public String uploadImage(MultipartFile file) throws IOException {

        //校验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTET_TYPES.contains(contentType)) {
            log.error("文件类型不合法:{}", originalFilename);
            throw new RuntimeException();
        }
        //校验文件内容
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bufferedImage == null) {
            log.error("文件内容不合法:{}", originalFilename);
        }
        //保存到服务器
        //文件名后缀
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), suffix, null);
        return "http://image.piketao.com/"+storePath.getFullPath();
    }
}
